<template>
	<view class="goods-container" v-if="goodsDetail">
		<!-- 轮播图 -->
		<swiper class="swiper-container" v-if="bannerList" :indicator-dots="true" circular="true" :autoplay="true"
			:interval="3000" :duration="1000">
			<swiper-item v-for="(item,index) in bannerList" :key="item">
				<image :src="item" mode="" @click="previewImage(index)" />
			</swiper-item>
		</swiper>
		<!-- 内容 -->
		<view class="content">
			<van-tag class="van-tag" size="large" type="danger">自营</van-tag>
			<text>{{goodsDetail.proname}}</text>
			<view class="price">￥{{format.formatPrice(goodsDetail.originprice)}}</view>
		</view>

		<!-- 商品导航 -->
		<van-goods-action>
			<van-goods-action-icon icon="chat-o" text="客服" dot />
			<van-goods-action-icon icon="cart-o" text="购物车" v-if="store.allGoodsNum" :info="store.allGoodsNum"
				@click="goToCart" />
			<van-goods-action-icon icon="cart-o" text="购物车" v-else @click="goToCart" />
			<van-goods-action-icon icon="shop-o" text="店铺" />
			<van-goods-action-button text="加入购物车" type="warning" @click="addGoods" />
			<van-goods-action-button text="立即购买" />
		</van-goods-action>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from "vue";
	import { getGoodsDetail } from '../../api/goodsDetail';
	import { Goods } from '../../types/home';
	import { useCartStore } from '../../stores/cart'
	import { useFormat } from '../../hooks';

	const store = useCartStore()
	const format = useFormat()

	const goodsDetail = ref({} as Goods)
	const bannerList = ref([])

	onLoad((options) => {
		getGoodsDetailData(options.proid)
	})

	// 获取商品详情
	const getGoodsDetailData = async (proid : string) => {
		const res = await getGoodsDetail(proid)
		goodsDetail.value = res.data
		bannerList.value = res.data.banners[0].split(',')

		uni.setNavigationBarTitle({
			title: res.data.proname
		})
	}

	// 图片预览
	const previewImage = (index : number) => {
		uni.previewImage({
			urls: bannerList.value,
			current: index
		})
	}

	// 跳转购物车
	const goToCart = () => {
		uni.switchTab({
			url: '/pages/cart/cart'
		})
	}

	// 加入购物车
	const addGoods = () => {
		const { proname, proid, originprice, img2 } = goodsDetail.value
		const goods = { proname, proid, price: originprice, img: img2, num: 1, checked: true }
		store.addToCart(goods)

		uni.showToast({
			title: '添加成功',
			icon: 'success'
		})
	}
</script>

<style scoped lang="scss">
	/* subPage/gooodsDetail/goodsDetail.wxss */
	.swiper-container {
		width: 750rpx;
		height: 600rpx;
	}

	.swiper-container swiper-item {
		width: 750rpx;
		height: 600rpx;
	}

	.swiper-container swiper-item image {
		width: 100%;
		height: 100%;
	}

	.content {
		margin-top: 20rpx
	}

	.content .van-tag {
		margin: 0 20rpx;
	}

	.content .price {
		font-size: 20px;
		font-weight: 888;
		color: red;
		margin-top: 40rpx
	}
</style>